package watchdog;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import log.LogFile;

import compute.ComputeRawTunesMain;

import drive.DriveLocations;

public class Main {

	private static final File INPUT_DIR = new File(DriveLocations.CLYDE
			+ "/Music/Temp");
	private static final File OK_DB_DIR = new File(DriveLocations.CLYDE
			+ "/Music/Util/98DB DONE");

	private File[] currentFileList;
	private File[] nextFileList;

	private void run(String[] args) throws InterruptedException {

		waitForClyde();

		currentFileList = getMP3List();

		while (true) {
			Thread.sleep(1000);
			nextFileList = getMP3List();
			compareListsAndProcessAddedFiles();
			currentFileList = nextFileList;
		}
	}

	private void waitForClyde() {
		println("Waiting for Clyde...");
		File clyde = new File(DriveLocations.CLYDE);

		while (!clyde.exists()) {
			// Wait
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		println("Clyde available.");
		println();
	}

	private void compareListsAndProcessAddedFiles() {
		for (int i = 0; i < nextFileList.length; i++) {

			File nextMp3 = nextFileList[i];
			boolean found = false;

			for (int j = 0; (j < currentFileList.length) && (!found); j++) {
				found = nextMp3.getName().equals(currentFileList[j].getName());
			}

			if (!found) {
				println("Found new mp3 : \"" + nextMp3.getName() + "\"");

				ComputeRawTunesMain computer = new ComputeRawTunesMain();
				computer.computeMp3File(nextMp3);
			}
		}
	}

	private static void println() {
		println("");
	}

	private static void println(String message) {
		System.out.println(message);
		LogFile.logln(message);
	}

	private void displayProcessResult(Process p) {
		byte[] text = new byte[1024];
		int num = 1;

		while (num > 0) {
			try {
				num = p.getErrorStream().read(text, 0, 1024);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (num > 0) {
				String result = new String(text, 0, num);
				System.out.print(result);
			}
		}
	}

	private File[] getMP3List() {
		return INPUT_DIR.listFiles(new FilenameFilter() {

			@Override
			public boolean accept(File file, String name) {
				return name.endsWith(".mp3");
			}
		});
	}

	public static void main(String[] args) throws InterruptedException {
		Date date = Calendar.getInstance().getTime();
		SimpleDateFormat format = new SimpleDateFormat("dd-MM-YYYY HH:mm");
		println("Watchdog STARTED on " + format.format(date));
		println();
		new Main().run(args);
		println("DONE.");
	}
}

// p = Runtime
// .getRuntime()
// .exec(new String[] { "cmd.exe", "/c", "start",
// "E:\\Documents\\java\\MP3WatchDog\\Resources\\runMP3Gain.bat" });
// E:\Documents\java\MP3WatchDog\Resources\runMP3Gain.bat